<template>
  <div class="app-container flex-col" v-loading="pageLoading">
    <div class="p-20">
      <el-row :gutter="30">
        <el-col :span="12">
          <emp-scan :data="initData" :focus.sync="empFocus" @onClear="onClearGroupOrEmp" @onChange="afterScanEmp">
          </emp-scan>
        </el-col>
        <el-col :span="12">
          <el-form inline>
            <div class="flex flex-center">
              <label class="mr-15">线别</label>
              <el-select class="mr-15 flex1" @change="afterScanEmp" v-model="initData.line" placeholder="请选择">
                <el-option v-for="l in lineOptions" :key="l.id" :value="l.id" :label="l.line_name"></el-option>
              </el-select>
              <!-- <el-input class="mr-15 flex1" v-model="initData.line_name" disabled>
              </el-input> -->
              <label class="mr-15">工站</label>
              <el-input class="mr-15 flex1" v-model="initData.group_name" disabled>
              </el-input>
            </div>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <div class="p-20 z-border-t">
      <div class="flex flex-center">
        <span class="mr-20">请扫描条码</span>
        <el-input class="flex1 z-scan" v-model="scanData" ref="scan" @keyup.enter.native="afterScan" size="large"
          :disabled="!canScan"></el-input>
      </div>
    </div>
    <div class="flex1 flex z-border-t" style="overflow-x: hidden; overflow-y: auto;">
      <div class="z-panel p-20 z-border-r flex1">
        <div class="flex flex-col-between mb-10">
          <div class="z-panel-title">待修信息</div>
          <el-button v-show="errorList.length" type="warning" round @click="changeKPN">换料</el-button>
        </div>
        <div class="z-panel-body">
          <el-table ref="errorTable" :data="errorList" border style="width: 100%" highlight-current-row
            row-key="repair_detail_id" @current-change="handleDetailClick">
            <el-table-column prop="serial_number" label="产品序号" v-if="initData.bind_status == 1"> </el-table-column>
            <el-table-column prop="error_code" label="不良代码"> </el-table-column>
            <el-table-column prop="error_description" label="不良描述"> </el-table-column>
            <el-table-column prop="error_qty" label="不良数量" v-if="initData.batch_qty > 1" width="120"></el-table-column>
            <el-table-column prop="repair_status" label="状态" width="100">
              <template slot-scope="scope">
                <span class="text-label" :class="scope.row.repair_status == 'Y'?'bg-green':'bg-yellow'">
                  {{scope.row.repair_status == 'Y'?'完成':'待修'}}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="p-20 z-panel" style="width: 40%;">
        <div class="z-panel-title">维修详情</div>
        <div class="z-panel-body">
          <template v-if="currentRepairData.repair_status=='Y'">
            <div class="z-info-item">
              <div class="z-info-label">维修人</div>
              <div class="z-info-value">{{currentRepairData.repairer}}</div>
            </div>
            <div class="z-info-item">
              <div class="z-info-label">维修方式</div>
              <div class="z-info-value">{{currentRepairData.repair_reason}}</div>
            </div>
            <div class="z-info-item">
              <div class="z-info-label">维修时间</div>
              <div class="z-info-value">{{currentRepairData.repair_time}}</div>
            </div>
            <div class="z-info-item">
              <div class="z-info-label">不良总数</div>
              <div class="z-info-value">{{currentRepairData.error_qty}}</div>
            </div>
            <div class="z-info-item">
              <div class="z-info-label">维修OK数量</div>
              <div class="z-info-value">{{currentRepairData.repair_ok_qty}}</div>
            </div>
            <div class="z-info-item">
              <div class="z-info-label">无法维修数量</div>
              <div class="z-info-value">{{currentRepairData.repair_ng_qty}}</div>
            </div>
          </template>
          <template v-else-if="!!currentRepairData.repair_detail_id">
            <div class="z-info-item flex-center">
              <div class="z-info-label">不良总数</div>
              <div class="z-info-value">
                <el-input v-model="currentRepairData.error_qty" disabled></el-input>
              </div>
            </div>
            <div class="z-info-item flex-center">
              <div class="z-info-label">维修方式</div>
              <div class="z-info-value">
                <el-input ref="repair_reason" :rows="3" type="textarea" v-model="currentRepairData.repair_reason">
                </el-input>
              </div>
            </div>
            <template v-if="initData.batch_qty>1">
              <div class="z-info-item flex-center">
                <div class="z-info-label">维修OK数量</div>
                <div class="z-info-value">
                  <el-input-number v-model="currentRepairData.repair_ok_qty" :min="0" :step="1" @change="okChange">
                  </el-input-number>
                </div>
              </div>
              <div class="z-info-item flex-center">
                <div class="z-info-label">无法维修数量</div>
                <div class="z-info-value">
                  <el-input-number v-model="currentRepairData.repair_ng_qty" :min="0" :step="1" @change="ngChange">
                  </el-input-number>
                </div>
              </div>
              <div class="z-info-item flex-center">
                <div class="z-info-label"></div>
                <div class="z-info-value" style="text-align:right">
                  <el-button type="info" round :loading="submiting" @click="repairSubmit">完成维修</el-button>
                </div>
              </div>
            </template>
            <template v-else>
              <div class="z-info-item flex-center">
                <div class="z-info-label">维修OK?</div>
                <div class="z-info-value">
                  <el-switch v-model="singleRepairOk" active-color="#13ce66" inactive-color="#666666"></el-switch>
                </div>
              </div>
              <div class="z-info-item flex-center">
                <div class="z-info-label">操作</div>
                <div class="z-info-value ml-80" style="text-align:left">
                </div>
                <div class="z-info-value" style="text-align:right">
                  <el-button type="info" round :loading="submiting" @click="singleSubmit">提交</el-button>
                </div>
              </div>
            </template>
          </template>
        </div>
      </div>
    </div>
    <message-box :msgs="msgs"></message-box>
    <el-dialog width="70%" :submitLoading="submitLoading" :visible.sync="changeKPNDialog">
      <div class="mt-10 mb-10 t-18 text-white">请选择要换料的物料记录</div>
      <z-table :list="list" :tableProps="tableProps" :columns="columns">
      </z-table>
      <div class="mt-20 mb-10 t-18 text-white">请扫码物料条码</div>
      <el-input class="flex1 z-scan" v-model="scanDataChange" ref="scan" @keyup.enter.native="afterScan" size="large">
      </el-input>
      <div class="flex flex-col-between t-18 text-white mt-20 flex-center">
        <div>
          <span class="mr-10">物料:</span>V048 测试物料
        </div>
        <div>
          <span class="mr-10">数量</span>
          <el-input-number v-model="kpnForm.num"></el-input-number>
        </div>
      </div>
      <div class="text-right mt-20">
        <el-button type="primary" @click.native="submitChangeKPN" :loading="submitLoading">确认换料
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import lineGroup from '@/components/WinClient/lineGroup'
import empScan from '@/components/WinClient/empScan'
import messageBox from '@/components/WinClient/messageBox'
import mixinClient from '@/views/_common/mixinClient'
import dayjs from 'dayjs'
import zTable from '@/views/_common/table.vue'

import _ from 'lodash'
const defaultData = {
  line: '',
  group: '',
  group_name: '',
  emp: '',
  empName: '',
  bind_status: false,
  batch_qty: 1,
}
export default {
  name: 'repairNormal',
  mixins: [mixinClient],
  components: { lineGroup, empScan, messageBox, zTable },
  data() {
    return {
      pageLoading: false,
      initData: { ...defaultData },
      lineOptions: [],
      empFocus: false,
      scanData: '',
      msgs: [],
      snHistory: [],
      errorCodes: [],
      ngNum: '',
      errorList: [],
      currentRepairData: {},
      singleRepairOk: true,
      submiting: false,
      changeKPNDialog: false,
      fields: [],
      submitLoading: false,
      tableProps: {
        border: true,
        hideOperations: true,
        highlightCurrentRow: true,
        // opsColWith: 140, //不定义默认80
        // showSelection: true, // 是否开启复选
        // expandable: true, //是否展开行
        // showIndexCol: false, //是否显示索引列
        // indexColWidth: 50, //索引列宽度
      },
      columns: [
        { title: '料号', key: 'kpn', width: 140 },
        { title: '名称', key: 'name' },
        { title: '材料序号', key: 'model_name', width: 160 },
        { title: '采集工序', key: 'model_name', width: 160 },
        { title: '采集时间', key: 'model_name', width: 160 },
        { title: '数量', key: 'model_name', width: 160 },
        { title: '替代群组', key: 'model_name' },
      ],
      list: [
        { kpn: 'test1', name: 'zhansgan' },
        { kpn: 'test2', name: 'lisi' },
      ],
      scanDataChange: null,
      kpnForm: {},
    }
  },
  mounted() {
    this.checkEmp()
    this.$request(this.$api.line + 'getlistbypage', {}, 'get', true)
      .then((r) => {
        this.lineOptions = r.list
      })
      .catch(() => {})
  },
  methods: {
    changeKPN() {
      this.changeKPNDialog = true
    },
    submitChangeKPN() {},
    okChange() {
      if (isNaN(this.currentRepairData.repair_ok_qty)) return
      if (this.currentRepairData.repair_ok_qty > this.currentRepairData.error_qty)
        return this.showMessage('数量不能大于不良产品总数', true)
      this.currentRepairData.repair_ng_qty = this.currentRepairData.error_qty - this.currentRepairData.repair_ok_qty
    },
    ngChange() {
      if (isNaN(this.currentRepairData.repair_ng_qty)) return
      if (this.currentRepairData.repair_ng_qty > this.currentRepairData.error_qty)
        return this.showMessage('数量不能大于不良产品总数', true)
      this.currentRepairData.repair_ok_qty = this.currentRepairData.error_qty - this.currentRepairData.repair_ng_qty
    },
    checkEmp() {
      if (!this.initData.empName) {
        this.showMessage('请扫描作业员，')
        this.empFocus = true
        return
      } else {
        this.afterScanEmp(true)
      }
    },
    afterScanEmp(r) {
      if (r) {
        if (!this.initData.line) {
          return this.showMessage('请选择线别')
        }
        this.showMessage('请扫描待修产品序号', false)
        setTimeout(() => {
          this.$refs.scan.focus()
        }, 200)
      } else {
        this.showMessage('作业员不正确', true)
      }
    },
    afterScan() {
      this.scanData = this.scanData.trim()
      if (!this.scanData) {
        this.showMessage('没有扫描到任何内容', true)
        return
      }
      this.scanData = this.scanData.toUpperCase()
      if (this.scanData.toUpperCase() == 'UNDO') {
        this.undo()
        return
      }
      if (this.scanData.toUpperCase() == 'END') {
        //
      }
      this.errorList = []
      this.currentRepairData = {}
      this.pageLoading = true
      this.$request(this.$api.repair + 'getlistbysn', { sn: this.scanData }, 'get', true)
        .then((r) => {
          this.pageLoading = false
          this.initData.group = r.info.group
          this.initData.group_name = r.info.group_name
          this.initData.bind_status = r.info.bind_status
          this.initData.batch_qty = r.info.batch_qty
          this.errorList = r.detail
          this.goNextRecord()
        })
        .catch((e) => {
          this.pageLoading = false
          setTimeout(() => {
            this.$refs.scan.select()
          }, 200)
          this.showMessage(e.message, true)
        })
    },
    handleDetailClick(row) {
      this.pageLoading = true
      this.currentRepairData = {}
      this.$request(this.$api.repair + 'getbyid', { id: row.repair_detail_id }, 'get', true)
        .then((r) => {
          this.pageLoading = false
          this.currentRepairData = r
        })
        .catch((e) => {
          this.pageLoading = false
          this.showMessage(e.message, true)
        })
    },
    singleSubmit() {
      if (!this.currentRepairData.repair_reason) return this.showMessage('维修方式不能为空', true)
      this.currentRepairData.repair_ng_qty = this.singleRepairOk ? 0 : 1
      this.currentRepairData.repair_ok_qty = this.singleRepairOk ? 1 : 0
      this.repairSubmit()
    },
    repairSubmit() {
      let check =
        this.currentRepairData.repair_ok_qty + this.currentRepairData.repair_ng_qty - this.currentRepairData.error_qty
      if (check !== 0) return this.showMessage('维修ok数量与无法维修数量之和不等于不良品总数', true)
      this.submiting = true
      let data = {
        ...this.currentRepairData,
        emp: this.initData.emp,
        line: this.initData.line,
        group: this.initData.group,
      }
      this.$request(this.$api.repair + 'commit', data, 'post', true)
        .then((r) => {
          this.submiting = false
          this.errorList = r
          if (r.some((x) => x.repair_status == 'N')) this.goNextRecord()
          else {
            this.showMessage('维修完成，请继续扫描下个产品序号', false)
            this.clearScanData()
          }
        })
        .catch((e) => {
          this.submiting = false
          this.showMessage(e.message, true)
        })
    },
    goNextRecord() {
      let nextItem = this.errorList.find((x, i) => x.repair_status == 'N')
      if (nextItem != null) {
        this.$refs.errorTable.setCurrentRow(nextItem)
        this.showMessage('请继续填写维修信息')
        setTimeout(() => {
          this.$refs.repair_reason.focus()
        }, 200)
      }
    },
    onClearGroupOrEmp() {
      this.clearScanData()
      this.checkEmp()
    },
    undo() {
      this.clearScanData()
    },
    clearScanData() {
      this.scanData = ''
      this.errorList = []
      this.currentRepairData = {}
      setTimeout(() => {
        this.$refs.scan.focus()
      }, 200)
    },
  },
  computed: {
    canScan: function () {
      return !!this.initData.empName
    },
    canSelectLineAndGroup: function () {
      return !this.initData.line || !this.initData.group
    },
    canInputEmp: function () {
      return !this.initData.empName && this.initData.line && this.initData.group
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/styles/client.scss';
</style>
